package com.veepeak.server.api.web;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.veepeak.server.api.web.vo.UserVO;
import com.veepeak.server.common.JSONResult;
import com.veepeak.server.domain.Obd;
import com.veepeak.server.domain.User;
import com.veepeak.server.domain.UserObd;
import com.veepeak.server.domain.Vehicle;
import com.veepeak.server.dto.PageModel;
import com.veepeak.server.dto.mapper.UserMapper;
import com.veepeak.server.service.UserObdService;
import com.veepeak.server.service.UserService;
import com.veepeak.server.service.UserVehicleService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/web/user")
@Api(description = "用户接口")
public class UserWebApi {
    @Autowired
    private UserService userService;
    @Autowired
    private UserObdService userObdService;
    @Autowired
    private UserVehicleService userVehicleService;
    @Autowired
    private UserMapper userMapper;

    @PostMapping(name = "")
    public JSONObject list(HttpServletRequest request, PageModel pageModel){
        String searchValue = request.getParameter("search[value]");
        Page<User> users =  userService.datatables(pageModel.getPage(),pageModel.getLength(),searchValue);

        Page<UserVO> pages = users.map(user -> {
            UserVO vo = userMapper.toVo(user);
            return vo;
        });

        return JSONResult.toSuccessJson(new PageModel(pageModel.getDraw(),pages),"").getJSONObject("data");
    }

    @GetMapping(value = "/{userId}")
    public JSONObject detail(@PathVariable String userId){
        User user = userService.get(userId);
        List<UserObd> obds = userObdService.findByUserId(userId);
        List<Vehicle> vehicles = userVehicleService.findByUserId(userId);

        JSONObject result = new JSONObject();
        result.put("user",user);
        result.put("obds",obds);
        result.put("vehicles",vehicles);
        return JSONResult.toSuccessJson(result,"");
    }

    @PostMapping(value = "/create")
    public JSONObject create(HttpServletRequest request){
        try {
            String email = request.getParameter("email");
            String password = request.getParameter("password");
            User user =  userService.regist(email,password,"verifyCode");

            return JSONResult.toSuccessJson(userMapper.toVo(user),"");
        } catch (Exception e) {
            return JSONResult.toFailureJson(e.getMessage());
        }
    }
}
